package com.wibo.account;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.ant.liao.GifView;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKEvent;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.wibo.account.SendWeiboActivity.MyGeneralListener;
import com.wibo.common.CommentItem;
import com.wibo.common.FileDbHelper;
import com.wibo.common.Utility;
import com.wibo.common.WeiboItem;

import weibo4android.Comment;
import weibo4android.Count;
import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.os.RemoteException;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.text.ClipboardManager;
import android.text.Html;
import android.text.TextPaint;
import android.text.util.Linkify;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class WeiboDetailsActivity extends Activity implements OnClickListener {
	
	private LinearLayout mMainDetailLayout;
	private LinearLayout mLoadingLayout;
	
	private ImageView mBackBtnView;
	private ImageView mBackHomeBtnView;
	
	private LinearLayout mUserBtnLayout;
	private ImageView mHeadImage;
	private TextView mUsername;
	
	private TextView mWeiboText;
	private ImageView mWeiboImage;
	private RelativeLayout mWeiboImageLayout;
	private ImageView mLocationImage;
	private RelativeLayout mLocationLayout;
	
	private RelativeLayout mRootLayout;
	private TextView mRootWeiboText;
	private ImageView mRootWeiboImage;
	
	private TextView mTimeText;
	private TextView mSourceText;
	private LinearLayout mCommentLayout;
	private LinearLayout mTransmitLayout;
	private TextView mCommentCountText;
	private TextView mTransmitCountText;
	
	private RelativeLayout mMoreCommentLayout;
	private ProgressBar mMoreCommentProgress;
	
	//private ListView mCommentListView;
	private CUserManager mUserManager = null;
	
	private long mWeiboId = -1;
	private Status mWeiboStatus;
	private WeiboItem mWeiboData = null;
	private EmotionsParser mParser;
	
	private ArrayList<CommentItem> mCommentsList;
	//private CommentItemAdapter mCommentsListAdapter;

	private boolean mbRunning = false;
	
	public static final String TAG = "WeiboDetailsActivity";

	private static Weibo mWeibo = null;
	private static OAuthConstant mAuthConstant = null;
	
	protected FileDbHelper mDbHelper = null;
	
	private static final int SHOW_COMMENTS = 1;
	private static final int SHOW_COMMENTS_ERROR = -1;
	private static final int GET_WEIBO_FINISHED = 2;
	private static final int GET_WEIBO_MID_PIC_ERROR = -2;
	private static final int GET_WEIBO_LARGE_PIC_FINISHED = 3;
	private static final int GET_WEIBO_LARGE_PIC_ERROR = -3;
	private static final int GET_WEIBO_COUNT_FINISHED = 4;
	private static final int GET_WEIBO_COUNT_ERROR = -4;
	private Thread mThread = null;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			
			if(!mbRunning){

				Log.e(TAG, "stop by not running flag!");
	    		return;
	    	}
			
			switch (msg.what) {
			case SHOW_COMMENTS:
				//mCommentsListAdapter.notifyDataSetChanged();
				boolean isGetMore = true;
				if (msg.obj != null && ((String)msg.obj).equalsIgnoreCase(REFRESH_COMMENT)){
					isGetMore = false;
				}
				
				showComments(isGetMore);
				
				break;
			case SHOW_COMMENTS_ERROR:
				break;
			case GET_WEIBO_FINISHED:
				mUsername.setText(mParser.replace(mWeiboData.getmUserName(), 18, 18));
				mWeiboText.setText(mParser.replace(mWeiboData.getmWeiboText(), 18, 18));
				
				if (mWeiboData.getmRtrootText() != null && !mWeiboData.getmRtrootText().isEmpty()){
					mRootWeiboText.setText(mParser.highlight(mParser.replace(mWeiboData.getmRtrootUsername() + ": " + mWeiboData.getmRtrootText(), 18, 18),
							0, mWeiboData.getmRtrootUsername().length(), getResources().getColor(R.color.sky_blue))/*mParser.replace(mWeiboData.getmRtrootText(), 18, 18)*/);
					
					mRootLayout.setVisibility(RelativeLayout.VISIBLE);
				}else{
					mRootLayout.setVisibility(RelativeLayout.GONE);
				}
				
				
				mTimeText.setText(mWeiboData.getmSentTime());
				mSourceText.setText(Html.fromHtml(mWeiboData.getmClientName()));

				mCommentCountText.setText(mWeiboData.getmCommentCount());
				mTransmitCountText.setText(mWeiboData.getmTransmitCount());;
				
				if (mWeiboData.getmWeiboUserPic() != null) {
					mHeadImage.setImageBitmap(Utility.getBitmap(WeiboDetailsActivity.this, mWeiboData.getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC));
				}
				
				if (mWeiboData.getmWeiboMidPic() != null && !mWeiboData.getmWeiboMidPic().isEmpty()) {
//					if (mWeiboData.getmWeiboMidPic().toLowerCase().endsWith(".gif")){
//						GifView gv = (GifView) findViewById(R.id.weiboImageGifView);
//						File file = new File(Utility.getPicPath(WeiboDetailsActivity.this, mWeiboData.getmWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC));
//						if (!file.exists()){
//							gv.setGifImage(R.drawable.angry);
//						}else{
//							gv.setGifImage(Utility.getBytes(WeiboDetailsActivity.this, mWeiboData.getmWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC));
//						}
//						
//						mWeiboImage.setVisibility(ImageView.GONE);
//						gv.setVisibility(GifView.VISIBLE);
//					}else{
						mWeiboImage.setImageBitmap(Utility.getBitmap(WeiboDetailsActivity.this, mWeiboData.getmWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC));
						Bitmap bm = Utility.getBitmap(WeiboDetailsActivity.this, mWeiboData.getmWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC);
						if (bm != null) {
							int width = bm.getWidth(); 
							int height = bm.getHeight(); 
							mWeiboImage.setMaxWidth(width - getScreenWidth() > 0 ? getScreenWidth() : width);
							mWeiboImage.setMaxHeight(getImageHeight(width, height));
							mWeiboImage.setAdjustViewBounds(true);
							mWeiboImageLayout.setVisibility(RelativeLayout.VISIBLE);
							mWeiboImage.setVisibility(ImageView.VISIBLE);
						}
//					}
				}else{
					mWeiboImageLayout.setVisibility(RelativeLayout.GONE);
					mWeiboImage.setVisibility(ImageView.GONE);
				}

//				
//				if (mWeiboData.getmWeiboMidPic() != null) {
//					mWeiboImage.setImageBitmap(Utility.getBitmap(WeiboDetailsActivity.this, mWeiboData.getmWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.LARGE_PIC));
//				}
				
				if (mWeiboData.getmRtrootText() != null && !mWeiboData.getmRtrootText().isEmpty()) {
					if (mWeiboData.getmRtrootWeiboMidPic() != null && !mWeiboData.getmRtrootWeiboMidPic().isEmpty()){
						mRootWeiboImage.setImageBitmap(Utility.getBitmap(WeiboDetailsActivity.this, mWeiboData.getmRtrootWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC));
						Bitmap bm = Utility.getBitmap(WeiboDetailsActivity.this, mWeiboData.getmRtrootWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC);
						if (bm != null) {
							int width = bm.getWidth(); 
							int height = bm.getHeight(); 
							mRootWeiboImage.setMaxWidth(width - getScreenWidth() > 0 ? getScreenWidth() : width);
							mRootWeiboImage.setMaxHeight(getImageHeight(width, height));
							mRootWeiboImage.setAdjustViewBounds(true);
						}
					}
				}
				
				//String path = "http://api.map.baidu.com/staticimage?center=116.403874,39.914889&width=500&height=500&zoom=11&labels=%E6%B5%B7%E6%B7%80|116.487812,40.017524|%E6%9C%9D%E9%98%B3|%E5%A4%A7%E7%BA%A2%E9%97%A8|116.442968,39.797022|%E4%B8%B0%E5%8F%B0|116.275093,39.935251|116.28377,39.903743&labelStyles=%E6%B5%B7%E6%B7%80,1,32,0x990099,0xff00,1|%E4%B8%9C%E5%8C%97%E4%BA%94%E7%8E%AF,1,14,0xffffff,0x996600,1|%E6%9C%9D%E9%98%B3,1,14,,0xff6633,1|%E5%A4%A7%E7%BA%A2%E9%97%A8,1,32,0,0xffffff,1|%E6%9C%AA%E7%9F%A5%EF%BC%9F%EF%BC%81%23%EF%BF%A5%25%E2%80%A6%E2%80%A6%26*%EF%BC%88%EF%BC%89%EF%BC%81,1,14,0xff0000,0xffffff,1|%E4%B8%B0%E5%8F%B0%E5%A4%A7%E8%90%A5,1,24,0,0xcccccc,1|%E8%A5%BF%E5%9B%9B%E7%8E%AF,,14,0,0xffffff,|%E6%88%91%E4%BB%AC%E4%BC%9F%E5%A4%A7%E7%A5%96%E5%9B%BD%E9%A6%96%E9%83%BD%E5%8C%97%E4%BA%AC,1,25,0xffff00,0xff0000,0";
//				Utility.getImagePath(WeiboDetailsActivity.this, path, Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC);
				if (mWeiboData.getmLatitude() != null && !mWeiboData.getmLatitude().equalsIgnoreCase("-1.0") && !mWeiboData.getmLatitude().isEmpty() &&
						mWeiboData.getmLongitude() != null && !mWeiboData.getmLongitude().equalsIgnoreCase("-1.0") && !mWeiboData.getmLongitude().isEmpty()) {
					mLocationImage.setImageBitmap(Utility.getBitmap(WeiboDetailsActivity.this, Utility.getLocationUrl(mWeiboData.getmLongitude(), mWeiboData.getmLatitude()), String.valueOf(mWeiboData.getmWeiboId()), Utility.WEIBO_LOCATION_PIC));
					Bitmap bm = Utility.getBitmap(WeiboDetailsActivity.this, Utility.getLocationUrl(mWeiboData.getmLongitude(), mWeiboData.getmLatitude()), String.valueOf(mWeiboData.getmWeiboId()), Utility.WEIBO_LOCATION_PIC);
					if (bm != null) {
						int width = bm.getWidth(); 
						int height = bm.getHeight(); 
						mLocationImage.setMaxWidth(width - getScreenWidth() > 0 ? getScreenWidth() : width);
						mLocationImage.setMaxHeight(getImageHeight(width, height));
						mLocationImage.setAdjustViewBounds(true);
					}
					mLocationImage.setVisibility(ImageView.VISIBLE);
					mLocationLayout.setVisibility(RelativeLayout.VISIBLE);
				}
//					mMapView.setVisibility(MapView.VISIBLE);
//					GeoPoint geoPoint = new GeoPoint((int) (26.449446 * 1E6), (int) (106.682949 * 1E6));// 取得地图控制器对象，用于控制MapView 
//					MapController mapController = mMapView.getController();
//					// 设置地图的中心
//					mapController.setCenter(geoPoint);// 设置地图默认的缩放级别
//					mapController.setZoom(16);// 初始化
//				}else{
//					mMapView.setVisibility(MapView.GONE);
//				}
				mMainDetailLayout.setVisibility(LinearLayout.VISIBLE);
				mLoadingLayout.setVisibility(LinearLayout.GONE);
				break;
			case GET_WEIBO_MID_PIC_ERROR:
				break;
			case GET_WEIBO_LARGE_PIC_FINISHED:
				break;
			case GET_WEIBO_LARGE_PIC_ERROR:
				break;
			case GET_WEIBO_COUNT_FINISHED:
				mCommentCountText.setText(mWeiboData.getmCommentCount());
				mTransmitCountText.setText(mWeiboData.getmTransmitCount());;
				break;
			case GET_WEIBO_COUNT_ERROR:
				break;
			}
		}
	};
	
	
	
	private void setContentViewSkin() {
		int skin = mUserManager.getMySkin();
		switch (skin) {
		case 0:
			setContentView(R.layout.weibodetails);
			break;
		case 1:
			setContentView(R.layout.weibodetails_2);
			break;
		default:
			setContentView(R.layout.weibodetails);
			break;
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		mUserManager = CUserManager.getInstance(this);
		mbRunning = true;
		setContentViewSkin();
		
		if (mAuthConstant == null)
			mAuthConstant = OAuthConstant.getInstance();

		if (mWeibo == null)
			mWeibo = mAuthConstant.getWeibo();
		
		if (mDbHelper == null)
			mDbHelper = new FileDbHelper(this);
		
		mParser = new EmotionsParser(this);
		
		
		mMainDetailLayout = (LinearLayout) findViewById(R.id.mainDetailLayout);
		mMainDetailLayout.setVisibility(LinearLayout.GONE);
		mLoadingLayout = (LinearLayout) findViewById(R.id.LoadingLayout);
		
		mBackBtnView = (ImageView) findViewById(R.id.backImageBtn);
		mBackBtnView.setOnClickListener(this);
		mBackHomeBtnView = (ImageView) findViewById(R.id.backHomeImageBtn);
		mBackHomeBtnView.setOnClickListener(this);
		mUserBtnLayout = (LinearLayout) findViewById(R.id.UserHeadLayout);
		mUserBtnLayout.setOnClickListener(this);
		mHeadImage = (ImageView) findViewById(R.id.userHeadPic);
		mUsername = (TextView) findViewById(R.id.username);
		TextPaint tp = mUsername.getPaint(); 
    	tp.setFakeBoldText(true);
    	mUsername.setFocusable(true);
    	mUsername.setFocusableInTouchMode(true);
    	mUsername.requestFocus();
    	
    	mWeiboImageLayout = (RelativeLayout) findViewById(R.id.weiboImageLayout);
    	mWeiboImageLayout.setVisibility(RelativeLayout.GONE);
		mWeiboText = (TextView) findViewById(R.id.weiboText);
		mWeiboText.setAutoLinkMask(Linkify.ALL);
        mWeiboText.setLinkTextColor(getResources().getColor(R.color.sky_blue));
		mWeiboImage = (ImageView) findViewById(R.id.weiboImage);
		mWeiboImage.setVisibility(ImageView.GONE);
		mWeiboImage.setOnClickListener(this);
		mRootLayout = (RelativeLayout) findViewById(R.id.rootWeiboLayout);
		mRootWeiboText = (TextView) findViewById(R.id.rootWeiboText);
		mRootWeiboText.setOnClickListener(this);
		mRootWeiboText.setAutoLinkMask(Linkify.ALL);
		mRootWeiboText.setLinkTextColor(getResources().getColor(R.color.sky_blue));
		mRootWeiboImage = (ImageView) findViewById(R.id.rootWeiboImage);
		mRootWeiboImage.setOnClickListener(this);
		
//		mBMapManager = new BMapManager(getApplication());
//
//		mBMapManager.init("7CA0B05B8858B53EB6779C9D45E787B1352AFDDC",
//				null);

		mLocationLayout = (RelativeLayout) findViewById(R.id.locationLayout);
		mLocationLayout.setVisibility(RelativeLayout.GONE);
		mLocationImage = (ImageView) findViewById(R.id.locationImageView);
		mTimeText = (TextView) findViewById(R.id.timeText);
		mSourceText = (TextView) findViewById(R.id.sourceText);
		mCommentLayout = (LinearLayout) findViewById(R.id.commentLayout);
		mCommentLayout.setOnClickListener(this);
		mTransmitLayout = (LinearLayout) findViewById(R.id.transmitLayout);
		mTransmitLayout.setOnClickListener(this);
		mCommentCountText = (TextView) findViewById(R.id.commentCountText);
		mTransmitCountText = (TextView) findViewById(R.id.transmitCountText);
		
		mRootLayout = (RelativeLayout) findViewById(R.id.rootWeiboLayout);
		
		mMoreCommentLayout = (RelativeLayout) findViewById(R.id.moreCommentLayout);
		mMoreCommentLayout.setOnClickListener(this);
		mMoreCommentProgress = (ProgressBar) findViewById(R.id.moreCommentPro);
		mMoreCommentProgress.setVisibility(ProgressBar.GONE);
		
		//mCommentItemLayouts = new ArrayList<LinearLayout>();
		//mCommentListView = (ListView) findViewById(R.id.commentList);
		
//		mCommentsList = new ArrayList<CommentItem>();
//        mCommentsListAdapter = new CommentItemAdapter(this);
//        mCommentsListAdapter.setAdapterData(mCommentsList);
//        mCommentListView.setAdapter(mCommentsListAdapter);
		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			mWeiboId = extras.getLong("weiboId");
			
			if (mWeiboId > 0) {
				WeiboItem weiboItem = (WeiboItem) extras.get("weiboItem");
				if (weiboItem != null) {
					Log.i(TAG, "weiboItem got!");
					mWeiboData = weiboItem;
					
					sendMessage(GET_WEIBO_FINISHED, null);
					
					getAndShowWeibo();
					getWeiboDetailsCount(mWeiboId);
					getNewComments(mWeiboId);
				}else{
					getWeiboFromDB(mWeiboId);
				}
			}
		}
	}
	
	private void sendMessage(int what, Object obj) {
		Message msg = mHandler.obtainMessage(what, obj);
		mHandler.sendMessage(msg);
	}
	
	@Override
	protected void onDestroy(){
    	super.onDestroy();
    	mbRunning = false;

    	if(mGetPicThread != null){
    		if(mGetPicThread.isAlive()){
    			mGetPicThread.interrupt();
    		}
    		mGetPicThread = null;
    	}
    	
    	if(mGetCountThread != null){
    		if(mGetCountThread.isAlive()){
    			mGetCountThread.interrupt();
    		}
    		mGetCountThread = null;
    	}
    	
    	if(mGetNewCommentsThread != null){
    		if(mGetNewCommentsThread.isAlive()){
    			mGetNewCommentsThread.interrupt();
    		}
    		mGetNewCommentsThread = null;
    	}
//    	if(mAccountService != null){
//    		try{
//    			mAccountService.unregisterCallback(mAccountCallback);
//    		}catch(RemoteException e){
//    			e.printStackTrace();
//    		}
//    		unbindService(mAccountConnection);
//    		mAccountService = null;
//    	}
//    	if(mWaitDialog != null && mWaitDialog.isShowing()){
//    		mWaitDialog.cancel();
//    	}
    }

	private Thread mGetPicThread = null;
	private static boolean isGetPic = false;
	
	private void getAndShowWeibo() {
		isGetPic = false;
		if (mGetPicThread != null) {
			if (mGetPicThread.isAlive()) {
				mGetPicThread.interrupt();
			}
			mGetPicThread = null;
		}
		mGetPicThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				isGetPic = true;
				
				Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
				
				Utility.getImagePath(WeiboDetailsActivity.this, mWeiboData.getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC);
				
				if (mWeiboData.getmWeiboMidPic() != null && !mWeiboData.getmWeiboMidPic().isEmpty()){
					Utility.getImagePath(WeiboDetailsActivity.this, mWeiboData.getmWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC);
				}
				
//				if (mWeiboData.getmWeiboMidPic() != null && !mWeiboData.getmWeiboMidPic().isEmpty()){
//					Utility.getImagePath(WeiboDetailsActivity.this, mWeiboData.getmWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.LARGE_PIC);
//				}
				
				if (mWeiboData.getmRtrootText() != null && !mWeiboData.getmRtrootText().isEmpty()) {
					if (mWeiboData.getmRtrootWeiboMidPic() != null && !mWeiboData.getmRtrootWeiboMidPic().isEmpty()){
						Utility.getImagePath(WeiboDetailsActivity.this,mWeiboData.getmRtrootWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC);
					}
				}
				
				//String path = "http://api.map.baidu.com/staticimage?center=116.403874,39.914889&width=500&height=500&zoom=11&labels=%E6%B5%B7%E6%B7%80|116.487812,40.017524|%E6%9C%9D%E9%98%B3|%E5%A4%A7%E7%BA%A2%E9%97%A8|116.442968,39.797022|%E4%B8%B0%E5%8F%B0|116.275093,39.935251|116.28377,39.903743&labelStyles=%E6%B5%B7%E6%B7%80,1,32,0x990099,0xff00,1|%E4%B8%9C%E5%8C%97%E4%BA%94%E7%8E%AF,1,14,0xffffff,0x996600,1|%E6%9C%9D%E9%98%B3,1,14,,0xff6633,1|%E5%A4%A7%E7%BA%A2%E9%97%A8,1,32,0,0xffffff,1|%E6%9C%AA%E7%9F%A5%EF%BC%9F%EF%BC%81%23%EF%BF%A5%25%E2%80%A6%E2%80%A6%26*%EF%BC%88%EF%BC%89%EF%BC%81,1,14,0xff0000,0xffffff,1|%E4%B8%B0%E5%8F%B0%E5%A4%A7%E8%90%A5,1,24,0,0xcccccc,1|%E8%A5%BF%E5%9B%9B%E7%8E%AF,,14,0,0xffffff,|%E6%88%91%E4%BB%AC%E4%BC%9F%E5%A4%A7%E7%A5%96%E5%9B%BD%E9%A6%96%E9%83%BD%E5%8C%97%E4%BA%AC,1,25,0xffff00,0xff0000,0";
				if (mWeiboData.getmLatitude() != null && !mWeiboData.getmLatitude().equalsIgnoreCase("-1.0") && !mWeiboData.getmLatitude().isEmpty() &&
						mWeiboData.getmLongitude() != null && !mWeiboData.getmLongitude().equalsIgnoreCase("-1.0") && !mWeiboData.getmLongitude().isEmpty()) {
					Utility.getImagePath(WeiboDetailsActivity.this, Utility.getLocationUrl(mWeiboData.getmLongitude(), mWeiboData.getmLatitude()), String.valueOf(mWeiboData.getmWeiboId()), Utility.WEIBO_LOCATION_PIC);
				}
				
				sendMessage(GET_WEIBO_FINISHED, null);
				
				isGetPic = false;
			}
		});
		
		if (!isGetPic) {
			mGetPicThread.start();
		}
	}
	
	private Thread mGetCountThread = null;
	private static boolean isGettingCount = false;
	
	private void getWeiboDetailsCount(final long id) {
		mGetCountThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try{
					isGettingCount = true;
					List<Count> counts = mWeibo.getCounts(String.valueOf(id));
					if (counts != null) {
						for (Count count : counts) {
							if(mWeiboData.getmWeiboId() == count.getId()){
								mWeiboData.setmCommentCount(String.valueOf(count.getComments()));
								mWeiboData.setmTransmitCount(String.valueOf(count.getRt()));
								
								try {
									mDbHelper.open();
									mDbHelper.updateCount(mWeiboData.getmWeiboId(), String.valueOf(count.getComments()), String.valueOf(count.getRt()));
								}catch(SQLiteException e){
									e.printStackTrace();
								}finally{
									mDbHelper.close();
								}
								
								break;
							}
						}
					}
					sendMessage(GET_WEIBO_COUNT_FINISHED, null);
				}catch(WeiboException e){
					e.printStackTrace();
					sendMessage(GET_WEIBO_COUNT_ERROR, null);
				}finally{
					isGettingCount = false;
				}
			}
		});
		
		if (!isGettingCount) {
			mGetCountThread.start();
		}
	};
	
	private void getWeiboFromDB(long id){
		try {
			mDbHelper.open();
			
			Cursor weiboCursor = mDbHelper.getWeiboListData(mWeiboId);
			
			final int weib_id = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_ID);
			final int user_pic = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USER_PIC);
			final int weibo_pic = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_PIC);
			final int weibo_mid_pic = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_MID_PIC);
			final int weibo_large_pic = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_LARGE_PIC);
			final int original_weibo_pic = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ORIGINAL_WEIBO_PIC);
			final int root_weibo_mid_pic = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_MID_PIC);
			final int root_weibo_large_pic = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_LARGE_PIC);
			final int username = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USERNAME);
			final int weibo_text = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_TEXT);
			final int original_text = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ORIGINAL_TEXT);
			final int sent_time = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_SENT_TIME);
			final int client_name = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_CLIENT_NAME);
			final int comment_count = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_COMMENT_COUNT);
			final int transmit_count = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_TRANSMIT_COUNT);
	
			final int user_id = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USER_ID);
			final int root_username = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_USERNAME);
			final int root_weibo_id = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_WEIBO_ID);
			final int user_vip = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_VIP);
			final int root_user_id = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_UID);
			final int root_user_vip = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_VIP);
			final int longitude = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_LONGITUDE);
			final int latitude = weiboCursor
			.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_LATITUDE);
	
			final int add_data1 = weiboCursor.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ADD_DATA1);
			weiboCursor.moveToFirst();
			
			if (weiboCursor.getCount() == 1) {
				mWeiboData = new WeiboItem();
				
				mWeiboData.setmWeiboId(weiboCursor.getLong(weib_id));
				mWeiboData.setmWeiboUserPic(weiboCursor.getString(user_pic));
				mWeiboData.setmWeiboPic(weiboCursor.getString(weibo_pic));
				mWeiboData.setmWeiboMidPic(weiboCursor.getString(weibo_mid_pic));
				mWeiboData.setmWeiboLargePic(weiboCursor.getString(weibo_large_pic));
				mWeiboData.setmRtrootWeiboPic(weiboCursor
						.getString(original_weibo_pic));
				mWeiboData.setmRtrootWeiboMidPic(weiboCursor.getString(root_weibo_mid_pic));
				mWeiboData.setmRtrootWeiboLargePic(weiboCursor.getString(root_weibo_large_pic));
				mWeiboData.setmUserName(weiboCursor.getString(username));
				mWeiboData.setmWeiboText(weiboCursor.getString(weibo_text));
				mWeiboData.setmRtrootText(weiboCursor
						.getString(original_text));
				mWeiboData.setmSentTime(weiboCursor.getString(sent_time));
				mWeiboData.setmClientName(weiboCursor.getString(client_name));
				mWeiboData.setmCommentCount(weiboCursor
						.getString(comment_count));
				mWeiboData.setmTransmitCount(weiboCursor
						.getString(transmit_count));
				mWeiboData.setmUserId(weiboCursor.getLong(user_id));
				mWeiboData.setmRtrootUsername(weiboCursor.getString(root_username));
				mWeiboData.setmRtrootWeiboId(weiboCursor.getLong(root_weibo_id));
				mWeiboData.setmVLogo(weiboCursor.getString(user_vip).equalsIgnoreCase("true"));
				mWeiboData.setmRtrootUserId(weiboCursor.getLong(root_user_id));
				mWeiboData.setmRtrootVLogo(weiboCursor.getString(root_user_vip).equalsIgnoreCase("true"));
				mWeiboData.setmLongitude(weiboCursor.getString(longitude));
				mWeiboData.setmLatitude(weiboCursor.getString(latitude));
	
				sendMessage(GET_WEIBO_FINISHED, null);
				
				getAndShowWeibo();
				getWeiboDetailsCount(mWeiboId);
				getNewComments(mWeiboId);
			}else{
				getWeibo(mWeiboId);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			mDbHelper.close();
		}
	}
	
	Thread mGetWeiboThread = null;
	boolean mGettingWeibo = false;
	
	private void getWeibo(final long weiboId) {
		mGetWeiboThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				mGettingWeibo = true;
				try{
					Status status = mWeibo.showStatus(weiboId);
					List<Count> counts = mWeibo.getCounts(String.valueOf(weiboId));
					if (status != null && counts.size() == 1) {
						mWeiboData = new WeiboItem();
						
						mWeiboData.setmWeiboId(status.getId());
						mWeiboData.setmWeiboUserPic(status.getUser().getProfileImageURL().toString());
						mWeiboData.setmWeiboPic(status.getThumbnail_pic());
						mWeiboData.setmWeiboMidPic(status.getBmiddle_pic());
						mWeiboData.setmWeiboLargePic(status.getOriginal_pic());
						if (status.getRetweeted_status() != null) {
							mWeiboData.setmRtrootWeiboPic(status.getRetweeted_status().getThumbnail_pic());
							mWeiboData.setmRtrootWeiboMidPic(status.getRetweeted_status().getBmiddle_pic());
							mWeiboData.setmRtrootWeiboLargePic(status.getRetweeted_status().getOriginal_pic());
							mWeiboData.setmRtrootText(status.getRetweeted_status().getText());
							mWeiboData.setmRtrootUsername(status.getRetweeted_status().getUser().getName());
							mWeiboData.setmRtrootWeiboId(status.getRetweeted_status().getId());
							mWeiboData.setmRtrootUserId(status.getRetweeted_status().getUser().getId());
							mWeiboData.setmRtrootVLogo(status.getRetweeted_status().getUser().isVerified());
						}
						
						mWeiboData.setmUserName(status.getUser().getName());
						mWeiboData.setmWeiboText(status.getText());						
						mWeiboData.setmSentTime(Utility.formatDate(status
								.getCreatedAt()));
						mWeiboData.setmClientName(status.getSource());
						mWeiboData.setmCommentCount(String.valueOf(counts.get(0).getComments()));
						mWeiboData.setmTransmitCount(String.valueOf(counts.get(0).getRt()));
						mWeiboData.setmUserId(status.getUser().getId());			
						mWeiboData.setmVLogo(status.getUser().isVerified());			
						mWeiboData.setmLongitude(String.valueOf(status.getLongitude()));
						mWeiboData.setmLatitude(String.valueOf(status.getLatitude()));
						
						sendMessage(GET_WEIBO_FINISHED, null);
					}
					getAndShowWeibo();
					
					getNewComments(mWeiboId);
				}catch (WeiboException e) {
					e.printStackTrace();
				}finally{
					mGettingWeibo = false;
				}
			}
		});
		
		if (!mGettingWeibo) {
			mGetWeiboThread.start();
		}
	}
	
	public int getScreenHeight() {
		WindowManager manage = getWindowManager();
		Display display = manage.getDefaultDisplay();
		return display.getHeight();
	}
	
	public int getScreenWidth() {
		WindowManager manage = getWindowManager();
		Display display = manage.getDefaultDisplay();
		return display.getWidth();
	}

	private int getImageHeight(int width, int height) {
		if (width > getScreenWidth() - 20) {
			return ((getScreenWidth() - 20) * height) / width; 
		}
		
		return height;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.backImageBtn:
			finish();
			break;
		case R.id.backHomeImageBtn:
			Intent intent = new Intent(WeiboDetailsActivity.this, WiboMainTabActivity.class);
			startActivity(intent);
			finish();
			break;
		case R.id.UserHeadLayout:
			intent = new Intent(WeiboDetailsActivity.this, WiboUserDetailsActivity.class);
			Bundle bundle = new Bundle();
    		bundle.putLong("userId", mWeiboData.getmUserId());
    		intent.putExtras(bundle);
			startActivity(intent);
			break;
			
		case R.id.weiboImage:
			if (mWeiboData.getmWeiboMidPic() != null && !mWeiboData.getmWeiboMidPic().isEmpty()) {
				File file = new File(Utility.getImagePath(WeiboDetailsActivity.this, mWeiboData.getmWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC));
				if (file.exists() && !file.isDirectory()) {
					intent = new Intent();   
					intent.setAction(android.content.Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(file), "image/*");   
					startActivity(intent);  
				}
			}
			
			break;
		case R.id.rootWeiboImage:
			if (mWeiboData.getmRtrootWeiboMidPic() != null && !mWeiboData.getmRtrootWeiboMidPic().isEmpty()) {
				File file = new File(Utility.getImagePath(WeiboDetailsActivity.this, mWeiboData.getmRtrootWeiboMidPic(), Utility.WEIBO_MID_PIC, Utility.MIDDLE_PIC));
				if (file.exists() && !file.isDirectory()) {
					intent = new Intent();   
					intent.setAction(android.content.Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(file), "image/*");   
					startActivity(intent);  
				}
			}
			
			break;
		case R.id.commentLayout:
			intent = new Intent(WeiboDetailsActivity.this, SendWeiboActivity.class);
    		bundle = new Bundle();
    		bundle.putInt(SendWeiboActivity.SEND_WEIBO_TYPE, SendWeiboActivity.REPLY_COMMENT);
    		bundle.putLong("weiboId", mWeiboData.getmWeiboId());
    		bundle.putString("username", mWeiboData.getmUserName());
    		bundle.putString("text", mWeiboData.getmWeiboText());

			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case R.id.transmitLayout:
			intent = new Intent(WeiboDetailsActivity.this, SendWeiboActivity.class);
    		bundle = new Bundle();
    		bundle.putInt(SendWeiboActivity.SEND_WEIBO_TYPE, SendWeiboActivity.TRANSMIT_WEIBO);
    		bundle.putLong("weiboId", mWeiboData.getmWeiboId());
    		bundle.putString("username", mWeiboData.getmUserName());
    		bundle.putString("text", mWeiboData.getmWeiboText());
    		if (mWeiboData.getmRtrootText() != null){
    			bundle.putString("rootText", mWeiboData.getmRtrootText());
    			bundle.putString("rootUsername", mWeiboData.getmRtrootUsername());
    		}

			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case R.id.moreCommentLayout:
			mMoreCommentProgress.setVisibility(ProgressBar.VISIBLE);
			getNewComments(mWeiboId);
			break;
			
		case R.id.rootWeiboText:
			intent = new Intent(WeiboDetailsActivity.this, WeiboDetailsActivity.class);
    		bundle = new Bundle();
    		bundle.putLong("weiboId", mWeiboData.getmRtrootWeiboId());
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		}
		
//		for (int i = 0; i < mCommentItemLayouts.size(); i++) {
//			if (mCommentItemLayouts.get(i).getId() == v.getId()) {
//				Toast.makeText(this, String.valueOf(i), Toast.LENGTH_SHORT).show();
//				break;
//			}
//		}
	}
	
	private void addChildToComment(LinearLayout comment, LinearLayout layout) {
		comment.addView(layout, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
	}
	
	private int mCommentStart = 0;
	private static final String REFRESH_COMMENT = "refresh_comment";
	private Thread mGetNewCommentsThread = null;
    private boolean mIsGettingNewComments = false;
    private void getNewComments(final long weiboId) {
    	mGetNewCommentsThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				mIsGettingNewComments = true;
				try {
					// 获取前N条
					List<Comment> comments = null;
					String text = "";
					
					if (mCommentsList == null) {
						mCommentsList = new ArrayList<CommentItem>();
					}
					if (mCommentsList.size() > 0) {
						Paging paging = new Paging(1, 10);
						paging.setMaxId(mCommentsList.get(mCommentsList.size() - 1).getId() - 1);
						
						comments = mWeibo.getComments(String.valueOf(weiboId), paging);
					}else{
						comments = mWeibo.getComments(String.valueOf(weiboId));		
						text = REFRESH_COMMENT;
					}
					if (comments != null && comments.size() > 0) {
						ArrayList<CommentItem> commentItemList = new ArrayList<CommentItem>();
						
						for (Comment comment : comments) {
							CommentItem commentItem = new CommentItem();
							commentItem.setCreatedAt(Utility.formatDate(comment.getCreatedAt()));
							commentItem.setId(comment.getId());
							commentItem.setUserId(comment.getUser().getId());
							commentItem.setSource(comment.getSource());
							commentItem.setText(comment.getText());
							commentItem.setUsername(comment.getUser().getName());
							commentItem.setWeiboUserPic(comment.getUser().getProfileImageURL().toString());
							commentItem.setmVLogo(comment.getUser().isVerified());
							
							commentItem.setRootWeiboId(comment.getStatus().getId());
							commentItem.setRootUsername(comment.getStatus().getUser().getName());
							commentItem.setRootText(comment.getStatus().getText());
							
							commentItem.setmLatitude(String.valueOf(comment.getLatitude()));
							commentItem.setmLongitude(String.valueOf(comment.getLongitude()));
							
							commentItemList.add(commentItem);				
						}
						mCommentsList.addAll(commentItemList);
					}
//					
					sendMessage(SHOW_COMMENTS, text);
				}catch (WeiboException e) {

					e.printStackTrace();
				} finally {
					mIsGettingNewComments = false;
				}
			}
		});
    	if (!mIsGettingNewComments) {
    		mGetNewCommentsThread.start();
    	}
    }
    
	private int getItemSkin() {
		int skin = mUserManager.getMySkin();
		switch (skin) {
		case 0:
			return R.layout.commentitem;
		case 1:
			return R.layout.commentitem_2;
		default:
			return R.layout.commentitem;
		}
	}
    
    private void showComments(boolean isGetMore){
    	LinearLayout commentLayout = (LinearLayout) findViewById(R.id.commentlayout);

		final LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		LinearLayout layout;
		if (isGetMore) {
			commentLayout.removeAllViews();
			mCommentStart = 0;
		}
		
		for (int i = 0; i < mCommentsList.size(); i++){

			layout = new LinearLayout(WeiboDetailsActivity.this);
			layout = (LinearLayout) li.inflate(getItemSkin(), null);
			layout.setOnClickListener(this);
			
			TextView username = (TextView) layout.findViewById(R.id.Username);
	    	TextPaint tp = username.getPaint(); 
	    	tp.setFakeBoldText(true);
	    	
	    	TextView commentText = (TextView) layout.findViewById(R.id.commentTextView);
	    	
	    	TextView sentTime = (TextView) layout.findViewById(R.id.commentTime);
	    	ImageView addCommentImage = (ImageView) layout.findViewById(R.id.addCommentImage);
	    	
	    	final int index = i;
	    	addCommentImage.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(WeiboDetailsActivity.this, SendWeiboActivity.class);
            		Bundle bundle = new Bundle();
            		bundle.putInt(SendWeiboActivity.SEND_WEIBO_TYPE, SendWeiboActivity.COMMENT_COMMENT);
            		bundle.putLong("commentId", mCommentsList.get(index).getId());
            		bundle.putLong("weiboId", mWeiboId);
            		bundle.putString("username", mCommentsList.get(index).getUsername());
            		bundle.putString("text", mCommentsList.get(index).getText());

					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
	    	
	    	username.setText(mCommentsList.get(i).getUsername());
	    	commentText.setText(mParser.replace(mCommentsList.get(i).getText(), 18, 18));
	    	sentTime.setText(mCommentsList.get(i).getCreatedAt());
	    	
	    	
	    	layout.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					showCommentItemDialog(index);
				}
			});

	    	addChildToComment(commentLayout, layout);

			mCommentStart++;
		}
		
		mMoreCommentProgress.setVisibility(ProgressBar.GONE);
    }
    
    private void showCommentItemDialog(final int pos) {
		AlertDialog.Builder builder = new AlertDialog.Builder(WeiboDetailsActivity.this);
		builder.setTitle(mCommentsList.get(pos).getUsername());
		builder.setItems(R.array.commentItem_ary, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
            	switch (which) {
            	case 0:
            		Intent intent = new Intent(WeiboDetailsActivity.this, SendWeiboActivity.class);
            		Bundle bundle = new Bundle();
            		bundle.putInt(SendWeiboActivity.SEND_WEIBO_TYPE, SendWeiboActivity.COMMENT_COMMENT);
            		bundle.putLong("commentId", mCommentsList.get(pos).getId());
            		bundle.putLong("weiboId", mWeiboId);
            		bundle.putString("username", mCommentsList.get(pos).getUsername());
            		bundle.putString("text", mCommentsList.get(pos).getText());

					intent.putExtras(bundle);
					startActivity(intent);
            		break;
            	case 1:
            		intent = new Intent(WeiboDetailsActivity.this, WiboUserDetailsActivity.class);
        			bundle = new Bundle();
            		bundle.putLong("userId", mCommentsList.get(pos).getUserId());
            		intent.putExtras(bundle);
        			startActivity(intent);
            		break;
            	case 2:
            		ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
            		//clip.getText();    // 粘贴
            		clip.setText(mCommentsList.get(pos).getText());
            		Toast.makeText(WeiboDetailsActivity.this, getString(R.string.copySuc), Toast.LENGTH_SHORT).show();
            		break;
            	}
            	
			}
		});
		
		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {

			}

		});
		
		builder.show();
	}
	
}
